package cn.tedu.controller;

import cn.tedu.serivce.IAdService;
import cn.tedu.serivce.ICouponService;
import cn.tedu.serivce.IItemService;
import cn.tedu.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 测试异步 线程池控制器
 * @author Kiven
 * @date 20220309
 */
@RestController
@RequestMapping("/web/api")
@Slf4j
public class TestAsyncController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private ICouponService couponService;

    @Autowired
    private IAdService adService;



    @Autowired
    @Qualifier("asyncExecutor")
    private ThreadPoolTaskExecutor executorService;

    /**
     *   制造业务需求. 现在要把首页的信息加载到redis缓存中,否则就多线程查询多个业务.再返回
     *   其中需要商品list .优惠券list.广告轮播.
     * @return
     */
    @RequestMapping("/home")
    public JsonResult findIndexList(){
        // TODO redis模块暂时不增加
        long startTime = System.currentTimeMillis();
        //有返回值的多线程实现需要Callable.使用lambda表达式把结果list给到Callable


        Callable<List> itemListCallable = ()-> itemService.getItemList();
        Callable<List> couponListCallable = ()-> couponService.getCoupon();
        Callable<List> adListCallable = ()-> adService.getAdList();
        // JUC Java.util.concurrent

        // 封装一个任务
        FutureTask<List> itemListTask = new FutureTask<>(itemListCallable);
        FutureTask<List> couponListTask = new FutureTask<>(couponListCallable);
        FutureTask<List> adListTask = new FutureTask<>(adListCallable);

        // 提交任务给线程池
        executorService.submit(itemListTask);  //  非阻塞式的IO多路复用
        executorService.submit(couponListTask);
        executorService.submit(adListTask);

        Map<String,Object> resultMap = new HashMap<>();
        try {
            resultMap.put("itemList",itemListTask.get());

        }
        catch (Exception e){
            log.debug(e.getMessage());
        }
        try {
            resultMap.put("couponList",couponListTask.get());

        }catch (Exception e){
            System.out.println(1);
        }

        try {
            resultMap.put("adList",adListTask.get());
        }catch (Exception e){
            System.out.println(1);
        }



        long endTime = System.currentTimeMillis();
        log.debug("总计用时:"+(endTime - startTime));
        return new JsonResult(resultMap);
    }



}
